package com.pactera.redis.autoconfigure;

import com.alibaba.fastjson.parser.ParserConfig;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonRedisSerializer;
import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.SerializationFeature;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cache.CacheManager;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.CacheKeyPrefix;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.text.SimpleDateFormat;
import java.time.Duration;

/**
 * @author: liqingdian
 **/
@Configuration
public class RedisConfiguration {

    @Autowired
    private RedisProperties redisProperties;

    /**
     * retemplate相关配置
     */
    @Bean("redisTemplate")
    @ConditionalOnMissingBean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        // 配置连接工厂
        template.setConnectionFactory(redisConnectionFactory);
        //使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值（默认使用JDK的序列化方式）
        RedisSerializer redisSerializer;
        if (redisProperties.isJackson()) {
            redisSerializer = this.getJackson2JsonRedisSerializer(Object.class);
        } else {
            redisSerializer = this.getFastJsonRedisSerializer(Object.class);
        }
        // 值采用json序列化
        template.setValueSerializer(redisSerializer);
        //使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashValueSerializer(redisSerializer);
        template.setHashKeySerializer(new StringRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    @Bean
    @ConditionalOnMissingBean
    public CacheManager cacheManager(RedisConnectionFactory redisConnectionFactory) {
        RedisSerializer<String> stringSerializer = new StringRedisSerializer();
        RedisSerializer redisSerializer;
        if (redisProperties.isJackson()) {
            redisSerializer = this.getJackson2JsonRedisSerializer(Object.class);
        } else {
            redisSerializer = this.getFastJsonRedisSerializer(Object.class);
        }
        RedisCacheConfiguration config = RedisCacheConfiguration
                .defaultCacheConfig()
                .entryTtl(Duration.ofSeconds(redisProperties.getTtl()))
                .computePrefixWith(CacheKeyPrefix.simple())
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(stringSerializer))
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(redisSerializer));
        return RedisCacheManager
                .builder(redisConnectionFactory)
                .cacheDefaults(config)
                .build();
    }

    private <T> FastJsonRedisSerializer<T> getFastJsonRedisSerializer(Class<T> clazz) {
        FastJsonRedisSerializer fastJsonRedisSerializer = new FastJsonRedisSerializer(clazz);
        String acceptPackage = redisProperties.getAcceptPackage();
        if (StringUtils.isNotBlank(acceptPackage)) {
            if (!acceptPackage.endsWith(".")) {
                acceptPackage += ".";
            }
            // 建议使用这种方式，小范围指定白名单
            ParserConfig.getGlobalInstance().addAccept(acceptPackage);
        } else {
            // 全局开启AutoType，不建议使用
            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        }
        // 配置序列化策略
        FastJsonConfig fjc = new FastJsonConfig();
        fjc.setSerializerFeatures(
                SerializerFeature.WriteClassName,
                SerializerFeature.SortField,
                SerializerFeature.WriteMapNullValue,
                SerializerFeature.WriteDateUseDateFormat,
                SerializerFeature.WriteNullListAsEmpty,
                SerializerFeature.WriteNullStringAsEmpty,
                SerializerFeature.WriteBigDecimalAsPlain,
                SerializerFeature.WriteEnumUsingToString,
                SerializerFeature.SkipTransientField
        );
        fjc.setDateFormat("yyyy-MM-dd HH:mm:ss");
        fastJsonRedisSerializer.setFastJsonConfig(fjc);
        return fastJsonRedisSerializer;
    }

    private <T> Jackson2JsonRedisSerializer<T> getJackson2JsonRedisSerializer(Class<T> clazz) {
        Jackson2JsonRedisSerializer<T> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(clazz);
        ObjectMapper objectMapper = new ObjectMapper();
        //序列化的时候序列对象的所有属性
        objectMapper.setSerializationInclusion(JsonInclude.Include.ALWAYS);
        //反序列化的时候如果多了其他属性,不抛出异常
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        //如果是空对象的时候,不抛异常
        objectMapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false);
        //属性为null的转换
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        //取消时间的转化格式,默认是时间戳,可以取消,同时需要设置要表现的时间格式  
        objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
        objectMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
        objectMapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        objectMapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        return jackson2JsonRedisSerializer;
    }
}
